import ArticleItem from '@/components/ArticleItem';
import { useAppSelector } from '@/store';
import { articleListActionCreator } from '@/store/action/article';
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';
import { useEffect, useState, useRef } from 'react';
import { useDispatch } from 'react-redux';

type Props = {
  channel_id: number;
};

export default function ArticleList({ channel_id }: Props) {
  // console.log(12, channel_id);

  const { activeId } = useAppSelector((state) => state.channel);
  // console.log(15, activeId);

  const dispatch = useDispatch();
  const { articles } = useAppSelector((state) => state.articleList);
  // console.log(19, articles);

  const list = articles[channel_id]?.list;

  // 触发刷新时的处理函数
  const handleRefresh = async () => {
    await dispatch(
      articleListActionCreator({
        channel_id,
        isRefresh: true,
      })
    );
  };

  // 无线滚动组件，滚动触底加载更多数据
  const [hasMore, setHasMore] = useState(true);
  // 需要准备一个加载状态的变量，防止触底后发送多次无效请求
  const loading = useRef(false);
  const handleLoadMore = async () => {
    // 如果数据加载中，就返回
    if (loading.current) return;
    loading.current = true;
    try {
      // 发送请求获取更多数据，需要使用到上一次推荐()的事件戳，防止获取重复的新闻
      await dispatch(
        articleListActionCreator({
          channel_id,
          timestamp: articles[channel_id].timestamp,
        })
      );
    } catch {
      // 请求的参数时间戳没有的话，就停止加载
      setHasMore(false);
    }
    // 🕐 请求完成后，更新标记表示加载完毕
    loading.current = false;
  };

  // 调用获取文章列表的action
  useEffect(() => {
    // 如果有数据，就不用再去发请求了
    if (list) return;
    if (channel_id === activeId) {
      dispatch(
        articleListActionCreator({
          channel_id,
        })
      );
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [channel_id, activeId, dispatch, list]);
  // 💥 没有列表，先不渲染
  if (!list) return null;
  return (
    <div>
      {/* 下拉刷新组件 */}
      <PullToRefresh onRefresh={handleRefresh}>
        {list.map((item) => (
          <ArticleItem
            style={{ padding: 10 }}
            key={item.art_id}
            article={item}
          />
        ))}
        {/* 无限滚动组件 */}
        <InfiniteScroll loadMore={handleLoadMore} hasMore={hasMore} />
      </PullToRefresh>
    </div>
  );
}
